import React, { Component } from 'react';
import axios from 'axios';

export default class Record extends Component{
  constructor(){
    super();
    this.state = {
      edit: false
    };
  }

  handleToggle(){
    this.setState({
        edit: !this.state.edit
    });
  }

  handleEdit(event){
    const record = {
      date: this.refs.date.value,
      title: this.refs.title.value,
      amount: this.refs.amount.value
    };
    axios.put("https://5a54227777e1d20012fa0723.mockapi.io/api/v1/records/"+this.props.record.id, record).then(

        response => {
          this.setState({edit: false});
          this.props.handleEditRecord(this.props.record, response.data);
        }
    ).catch(
        error => console.log(error.message)
    )
  }

    handleDeleteRecord(){
      axios.delete("https://5a54227777e1d20012fa0723.mockapi.io/api/v1/records/"+this.props.record.id).then(

          response => {
              this.props.handleDeleteRecord(this.props.record);
          }
      ).catch(
          error => console.log(error.mesage)
      )
    }

  recordRow(){
    return (
        <tr>
          <td>{this.props.record.date}</td>
          <td>{this.props.record.title}</td>
          <td>{this.props.record.amount}</td>
          <td>
            <button onClick={this.handleToggle.bind(this)} className="btn btn-info mr-1">Edit</button>
            <button onClick={this.handleDeleteRecord.bind(this)} className="btn btn-danger">Delete</button>
          </td>
        </tr>
    );
  }



  recordForm(){
    return (
        <tr>
          <td><input type="text" className="form-control" defaultValue={this.props.record.date} ref="date"/></td>
          <td><input type="text" className="form-control" defaultValue={this.props.record.title} ref="title"/></td>
          <td><input type="text" className="form-control" defaultValue={this.props.record.amount} ref="amount"/></td>
          <td>
            <button onClick={this.handleEdit.bind(this)} className="btn btn-info mr-1">Update</button>
            <button onClick={this.handleToggle.bind(this)} className="btn btn-danger">Cancel</button>
          </td>
        </tr>
    );
  }

  render(){
    if(this.state.edit){
      return this.recordForm();
    }else{
      return this.recordRow();
    }
  }
}